<style>
    .font14{
        font-size : 14px;
        font-weight : 500;
        margin-right : 40px;
    }
    a:hover {
        cursor:pointer;
    }

</style>

<div class="container-fluid">
    <div class="wrapper">
        <div class="panel" id="nav">
            <div class="panel-heading">
                <h3 class="panel-title" id="ccc">备货需求申请</h3>
            </div>
            <div class="panel-body">
                <div>
                    <p>
                        <span style="color: #91bef0"><b>Tip:</b></span><br>
                        1.创建需求的时候如果提示SKU不存在，则需要找销售同事到平台SKU列表录入平台SKU与公司SKU对应关系;<br>
                        2.选项除了备注可为空之外，其他<span style="color: red">必填！</span><br>
                        3.可用库存为0并且所有站点可用库存为0不能下单，产生的原因有：实际库存为0、库存被其他帐号占用、还没有入库;<br>
                        4.可用库存为0但所有站点可用库存不为0可以进行<span style="color: red">库存调拨</span>,备货量不能超过总可用库存。<br>
                        5.不能选择帐号请到&nbsp;<span style="color: red">备货需求管理 > 销售员帐号对应关系表</span>，新增对应关系
                    </p>
                </div>
                <form class="form-inline" action="Inbound/StockingApply/prepare" id="option-form">
                    <div class="form-group">
                        <lable class="label-control font14">
                            申请人：<span><b>{$Think.session.current_account.remark}</b></span>
                            <input type="hidden" id="applyMan" value="{$Think.session.current_account.role_id}">
                        </lable>
                     </div>
                    <div class="form-group font14" id="siteName">
                        <label>店铺帐号：</label>
                        <select class="chosen-select form-control w200" tabindex="-1" name="accountId" 
                        data-name-group="common">
                            <option value="" class="empty-opt">-- 请选择 --</option>
                            <volist name="accounts" id="item">
                                <?php
                                    if ($accountId) {
                                ?>
                                <option value="{$item.id}"
                                <if condition="$item.id heq $accountId">selected="selected"</if>>{$item.accName}
                                </option>
                                <?php
                                    } else {
                                ?>
                                <option value="{$item.id}">{$item.accName}</option>
                                <?php
                                    }
                                ?>
                            </volist>
                        </select>
                    </div>
                </form>
                <div class="clearfix"></div>
                <hr>
                <div style="width:100%;overflow-x:scroll">
                    <table class="table table-striped  table-hover" cellspacing="0" width="2800px">
                    <thead>
                    <tr>
                        <!--<th>编号</th>-->
                        <th>SKU</th>
                        <th>是否退税</th>
                        <th>公司主体</th>
                        <th>发货仓库</th>
                        <th>产品名称</th>
                        <th>实际库存</th>
                        <th>实际可用库存</th>
                        <th>实际占用库存</th>
                        <th>所有站点可用库存</th>
                        <th>需求数量</th>
                        <th>要求到货时间</th>
                        <th>备注</th>
                        <th>操作</th>
                    </tr>
                    </thead>
                    <tbody id="html">
                    <tr>
                        <!--<td></td>-->
                        <td class="td_sku">
                            <input class="form-control w80 sku" type="text" autocomplete="off"
                                   onblur="skuInfoCheck(this)" />
                        </td>
                        <td class="td_tax">
                            <select type="text" name="tax" class="form-control option">
                                <option value="">请选择</option>
                                <option value="0">否</option>
                                <option value="1">是</option>
                            </select>
                        </td>
                        <td class="td_enterprise">
                            <select type="text" name="enterprise" class="form-control option">
                                <option value="">请选择</option>
                                <volist name="enterprise_dominant" id="item">
                                    <option value="{$key}">{$item}</option>
                                </volist>
                            </select>
                        </td>
                        <td class="address">
                            <select type="text" name="creater" class="form-control option">
                                <option>请选择</option>
                                <volist name="address" id="item">
                                    <option value="{$item.id}">{$item.name}</option>
                                </volist>
                            </select>
                        </td>
                        <td class="title"></td>
                        <td class="quantity"></td>
                        <td class="actualQuantity"></td>
                        <td class="occupyQuantity"><a></a></td>
                        <td class="totalActualQuantity"></td>
                        <td class="needQuantity"><input class="form-control w50 option input_quantity" type="text" /></td>
                        <td class="claimArriveTime"><input class="form-control Wdate w120" type="text" onClick="WdatePicker()"></td>
                        <td class="remark"><input class="form-control w80" type="text" /></td>
                        <td><button type="button" class="btn btn-info btn-sm add-space del">删除</button></td>
                    </tr>
                </table>
                </div>
                <div class="fixed-table-toolbar">
                    <h3>
                        <button type="button" class="btn btn-success" id="addRow">+ 新增</button>
                    </h3>
                </div>
                <div class="col-md-offset-5 col-md-2 add-space">
                    <button class="btn btn-primary" id="submit" >提交申请</button>
                </div>
            </div>
        </div>
    </div>
</div>

<script type="text/javascript">
    $(document).ready(function () {
        var tr_html = $("#html").html();
        var td_html = $("#html").children('tr').eq(0).html();
        $("#html").children('tr').eq(0).attr('name', 'firstRow');

        $('select.chosen-select').chosen({
            no_results_text : '没有找到',    // 当检索时没有找到匹配项时显示的提示文本
            disable_search_threshold : 2,  // 个以下的选择项则不显示检索框
            search_contains : true         // 从任意位置开始检索
        });

        //增加列
        $('#addRow').click(function () {
            $('tbody').append(tr_html);
        });

        //删除列，第一列清空
        $(document).on('click', '.del', function () {
            if ($(this).parent().parent().attr('name') == 'firstRow') {
                $(this).parent().parent().html(td_html);
                return;
            }
            $(this).parent().parent().remove();
        });

        $(document).on('blur', '.input_quantity', function () {
           if ($(this).val() != '') {
               var needQuantity = Number($(this).val());
               if (isNaN(needQuantity)) {
                   layer.msg("请输入数字！", {icon : 5});
                   return false;
               }
               if (needQuantity > $(this).parent().prevAll('.totalActualQuantity').text()) {
                   layer.msg("备货数字不能大于所有站点总可用量！", {icon : 5});
                   $(this).val($(this).parent().prevAll('.totalActualQuantity').text());
                   return false;
               }
           }
        });

        //选择框光标离开触发事件
        $(document).on('blur', '.option',  function () {
           if ($(this).val() == ''){
               layer.msg("请选择或者输入值！", {icon : 5});
               return false;
           }

           var td = $(this);
           var accountId = $('select[name="accountId"]').val();
           var checkflag = true;

           if ($(this).attr('name') == 'enterprise') {
               var tax = $(this).parent().prevAll('.td_tax').children().val();
               var sku = $(this).parent().prevAll('.td_sku').children('.sku').val();
               if (!sku) {
                   layer.msg('请先填写SKU！', {icon : 5});
                   clearRow(td, td_html);
                   return;
               }
               if (!tax) {
                   layer.msg("请先选择是否退税！", {icon : 5});
                   clearRow(td, td_html);
                   return;
               }

               if ((tax == 0 && $(this).val() != 1) || (tax == 1 && $(this).val() == 1)) {
                   layer.msg("主体选择错误，请重试！", {icon : 5});
                   clearRow(td, td_html);
                   return;
               }

               if ($(this).val() != 1) {
                   $.ajax({
                       type : "POST",
                       async : false,
                       url : "__URL__/checkWarehouseOrder?sku=" + sku + "&enterprise_dominant=" + $(this).val(),
                       dataType : "json",
                       success : function (data) {
                           if (!data.status) {
                               layer.msg(data.msg, {icon : 5});
                               clearRow(td, td_html);
                               checkflag = false;
                               return false;
                           }
                       }
                   });

                   if (checkflag == false) return false;

                   $.ajax({
                       type : "POST",
                       async : false,
                       url : "__URL__/checkPurchaseOrder?sku=" + sku + "&enterprise_dominant=" + $(this).val(),
                       dataType : "json",
                       success : function (data) {
                            if (data.allow) {
                                layer.msg(data.allow, {icon : 1})
                            } else {
                                if (data.deny) {
                                    layer.msg(data.deny, {icon : 5});
                                    clearRow(td, td_html);
                                    checkflag = false;
                                    return false;
                                }
                            }
                       }

                   });
               }

               if (checkflag == false) return false;
               $.ajax({
                   type: "POST",
                   async : false,
                   url: "__URL__/skuInventoryGet?sku=" + sku + '&export_tax_rebate=' + tax
                        + '&enterprise_dominant=' + $(this).val() +'&account_id=' + accountId,
                   dataType: "json",
                   success: function (data) {
                       if (data) {
                           td.parent().nextAll('.quantity').text(data.quantity);
                           td.parent().nextAll('.actualQuantity').text(data.actualQuantity);
                           td.parent().nextAll('.occupyQuantity').children().text(data.occupyQuantity);
                           td.parent().nextAll('.totalActualQuantity').text(data.totalActualQuantity);
                           if (data.actualQuantity <= 0 && data.totalActualQuantity <= 0) {
                               layer.msg("可用库存为0或已被占用，不能申请备货！", {icon : 5});
                               clearRow(td, td_html);
                           }
                       } else {
                           layer.msg("获取库存数据失败，请联系IT！", {icon : 5});
                       }
                   }
               })
           }

        });

        $(".occupyQuantity").click(function () {
            var sku = $(this).prevAll('.td_sku').children('.sku').val();
            var export_tax_rebate = $(this).prevAll('.td_tax').children().val();
            var enterprise_dominant = $(this).prevAll('.td_enterprise').children().val();
            window.open("__URL__/occupiedInventory?sku=" + sku
                    + "&export_tax_rebate=" + export_tax_rebate
                    + "&enterprise_dominant=" + enterprise_dominant);
        });

/*         //选择帐号之后联动查出销售员
        $('select[name="accountId"]').change(function () {
            if ($("#applyMan").val() !=4) {
                var accountId = $(this).val();
                if (accountId != '') {
                    window.location.href = "__URL__/prepare?accountId=" + accountId;
                }
            }
        }); */

        //提交备货申请
        $('#submit').click(function () {
        	var accountId = $('select[name="accountId"]').val();
            if(!accountId) {
                layer.msg('请选择店铺帐号!', {icon: 5});
                return false;
            }
            var confirm = window.confirm("您确定要提交吗？");
            if (!confirm) {
                return false;
            }
            var flag = true;
            $('#html').children('tr').each(function () {
                $(this).children('td').children('.option').each(function () {
                    if ($(this).val() == '') {
                        flag = false;
                        layer.msg("[" +
                                $(this).parent().prevAll('.td_sku').children('.sku').val()
                                + "]:信息未完整！");
                        return false;
                    }
                });
                if (flag == false){
                    return false;
                }
            });

            if (flag == false){
                return false;
            }

            stockingApplySubmit($('#html').children('tr'));
        });
    });

    function clearRow(td, td_html) {
        if (td.parent().parent().attr('name') == 'firstRow') {
            td.parent().parent().html(td_html);
            return;
        }
        td.parent().parent().remove();
        return false;
    }

    /* function doAutoComplete(skuInputObj) {
        var accountId = $('select[name="accountId"]').val();

        if(!accountId) {
            layer.msg('请选择帐号!', {icon: 5});
            return;
        }

        if (!$(skuInputObj).attr('readonly')) {
            $(skuInputObj).autocomplete({
                autoFocus: true,
                minLength: 0,
                autoFill: true,
                source: "__URL__/skuAutoComplete?accountId=" + accountId + '&skuKeywords=' + $(skuInputObj).val(),
                select: function (event, ui) {
                    $.ajax({
                        type: "POST",
                        url: "__URL__/skuInfoGet?sku=" + ui.item.sku,
                        dataType: "json",
                        success: function (data) {
                            $(skuInputObj).parent().nextAll('.title').text(data.name);
                        },
                        error: function () {
                            layer.msg("SKU标题不存在!", {icon: 5});
                        }
                    })
                }
            });
        }
    } */

    /**
     * 描述：检查SKU是否存在
     */
    function skuInfoCheck(skuInputObj) {
        var accountId = $('select[name="accountId"]').val();
        if(!accountId) {
            layer.msg('请选择店铺帐号!', {icon: 5});
            return false;
        }

        if (!$(skuInputObj).attr('readonly') && $(skuInputObj).val().trim() != '') {
            $.ajax({
                type : "POST",
                url : "__URL__/skuCheck?accountId=" + accountId + '&skuKeywords=' + $(skuInputObj).val(),
                dataType: 'json',
                success : function (data) {
                    if (data && data.sku) {
                        $(skuInputObj).val(data.sku);
                        $(skuInputObj).parent().nextAll('.title').text(data.name);
                        $(skuInputObj).attr("readonly", "readonly");
                    } else {
                        layer.msg('该SKU不存在，请去平台SKU列表下录入！', {icon : 5});
                        return false;
                    }
                }
            })
        }
    }

    /**
     * @param stockingApply
     * 描述：提交备货申请
     */
    function stockingApplySubmit(stockingApply) {
        var stockingApplyArray = [];
        stockingApply.each(function () {
            var stockingApplyObj = {};
            stockingApplyObj.account_id = $('select[name="accountId"]').val();
            stockingApplyObj.sku = $(this).children('.td_sku').children('input').val();
            stockingApplyObj.export_tax_rebate = $(this).children('.td_tax').children().val();
            stockingApplyObj.enterprise_dominant = $(this).children('.td_enterprise').children().val();
            stockingApplyObj.transfer_hopper_id = $(this).children('.address').children().val();
            stockingApplyObj.sku_name = $(this).children('.title').text();
            stockingApplyObj.needs_quantity = $(this).children('.needQuantity').children().val();
            stockingApplyObj.claim_arrive_time = $(this).children('.claimArriveTime').children().val();
            stockingApplyObj.remark = $(this).children('.remark').children().val();
            stockingApplyArray.push(stockingApplyObj);
        });

        $.ajax({
            type : "POST",
            url : "__URL__/stockingApplyInsert",
            data : {data : JSON.stringify(stockingApplyArray)},
            dataType : "JSON",
            success : function (data) {
                if (data['status'] == 1) {
                    layer.msg(data['message'], {icon : 1});
                } else {
                    layer.alert(data['message'], {icon : 5});
                }
                window.location.reload();
            },
            error : function () {
                layer.alert("提交失败！", {icon : 5});
                window.location.reload();
            }
        })
    }
</script>